<template>
	<view class="cpatrol-page">
		<!-- 页面头部 -->
		<view class="page-header">
			<view class="header-content">
				<text class="page-title">📋 巡查单管理</text>
				<text class="task-count">{{ cpatrolList.length }} 个巡查单</text>
			</view>
			<view class="header-actions">
				<view 
					v-if="canAddPatrol" 
					class="action-btn add-btn" 
					@click="addcapatrol"
				>
					<text class="btn-icon">➕</text>
					<text class="btn-text">新增巡查单</text>
				</view>
				<view class="action-btn filter-btn" @click="chargeFilter">
					<text class="btn-icon">🔍</text>
					<text class="btn-text">{{ showFilter ? '收起筛选' : '筛选查询' }}</text>
				</view>
			</view>
		</view>
		
		<!-- 筛选区域 -->
		<view v-if="showFilter" class="filter-section">
			<view class="filter-card">
				<view class="filter-title">筛选条件</view>
				<view class="filter-content">
					<view class="filter-row">
						<text class="filter-label">巡查结果：</text>
						<picker 
							class="filter-picker" 
							@change="bindPresultChanges" 
							range-key="cn"
							:value="presultindex" 
							:range="presults"
						>
							<text class="picker-text">{{ (presults[presultindex] && presults[presultindex].cn) || '选择结果' }}</text>
						</picker>
					</view>
					<view class="filter-row">
						<text class="filter-label">巡查模式：</text>
						<picker 
							class="filter-picker" 
							@change="bindPickerChanges" 
							range-key="cn"
							:value="index" 
							:range="pModes"
						>
							<text class="picker-text">{{ (pModes[index] && pModes[index].cn) || '选择模式' }}</text>
						</picker>
					</view>
					<view class="filter-actions">
						<view class="filter-btn primary" @click="filter">查询</view>
						<view class="filter-btn secondary" @click="resetFilter">重置</view>
					</view>
				</view>
			</view>
		</view>
		<!-- 空状态 -->
		<view v-if="!isLoading && cpatrolList.length === 0" class="empty-state">
			<text class="empty-icon">📋</text>
			<text class="empty-title">暂无巡查单</text>
			<text class="empty-desc">当前项目暂无巡查记录</text>
			<view v-if="canAddPatrol" class="empty-action" @click="addcapatrol">
				<text class="action-text">+ 创建新的巡查单</text>
			</view>
		</view>

		<!-- 巡查单列表 -->
		<view v-else class="patrol-list">
			<view 
				v-for="(item, index) in cpatrolList" 
				:key="item.pid || index" 
				class="patrol-card"
				@click="updateCpatrol(item)"
			>
				<!-- 卡片头部 -->
				<view class="card-header">
					<view class="task-time">
						<text class="time-icon">📅</text>
						<text class="time-text">{{ formatTime(item.inserttime) }}</text>
					</view>
					<StatusBadge 
						:text="item.presult || '未知'" 
						:type="getResultType(item.presult)"
					/>
				</view>

				<!-- 项目名称 -->
				<view class="project-name">
					<text class="name-text">{{ item.cproject || '未知项目' }}</text>
				</view>

				<!-- 巡查信息 -->
				<view class="patrol-info">
					<view class="info-row">
						<text class="info-label">📝 单号</text>
						<text class="info-value">{{ item.pid || '--' }}</text>
					</view>
					<view class="info-row">
						<text class="info-label">📋 类型</text>
						<text class="info-value">{{ item.ptype || '--' }}</text>
					</view>
					<view class="info-row">
						<text class="info-label">🔍 模式</text>
						<text class="info-value">{{ item.pmode || '--' }}</text>
					</view>
					<view class="info-row">
						<text class="info-label">👤 巡查人</text>
						<text class="info-value">{{ item.pman1 || '--' }}</text>
					</view>
					<view class="info-row">
						<text class="info-label">⏰ 巡查时间</text>
						<text class="info-value">{{ formatDateTime(item.patroltime) }}</text>
					</view>
					<view class="info-row">
						<text class="info-label">📊 流程节点</text>
						<text class="info-value flow-node">{{ getFlowNodeName(item.rf_flow_node) }}</text>
					</view>
				</view>

				<!-- 操作提示 -->
				<view class="action-hint">
					<text class="hint-text">点击查看详情或编辑</text>
				</view>
			</view>
		</view>

		<!-- 加载状态 -->
		<LoadingSpinner v-if="isLoading" :overlay="true" text="加载中..." />
	</view>
</template>

<script>
	import { request } from '@/request/index.js'
	import StatusBadge from '@/components/common/StatusBadge.vue'
	import LoadingSpinner from '@/components/common/LoadingSpinner.vue'
	import { FLOW_NODES } from '@/constants/index.js'
	import { formatDate, formatDateTime } from '@/utils/index.js'
	
	export default {
		name: 'CpatrolPage',
		components: {
			StatusBadge,
			LoadingSpinner
		},
		data() {
			return {
				cpatrolList: [],
				showFilter: false,
				isLoading: false,
				
				// 筛选相关
				pmode: '',
				pModes: [],
				index: 0,
				presult: '',
				presults: [],
				presultindex: 0,
				cproject: '',
				cprojects: [],
				cprojectIndex: 0,
				
				userInfo: {},
				cprojectId: ''
			}
		},
		computed: {
			canAddPatrol() {
				if (!this.userInfo.role) return false
				const roleName = this.userInfo.role.name
				return roleName === '市场监督员' || 
					   roleName === '安全监督员' || 
					   roleName === '质量监督员'
			}
		},
		show(){
			this.getCpatrol()
		},
		onLoad(option) {
			const userInfo = uni.getStorageSync('user')
			if (!userInfo || userInfo === 'null' || userInfo === '') {
				uni.showToast({
					title: '请先登录',
					success() {
						uni.reLaunch({
							url: '/pages/login/login'
						})
					}
				})
				return
			}
			
			this.userInfo = userInfo
			this.cprojectId = option.cprojectId
			this.initData()
		},
		onPullDownRefresh() {
			this.getCpatrol({})
			setTimeout(() => {
				uni.stopPullDownRefresh()
			}, 800)
		},
		methods: {
			async initData() {
				await Promise.all([
					this.getCpatrol({}),
					this.getPmode(),
					this.getPresults(),
					this.getProjects()
				])
			},
			
			formatTime(timeStr) {
				if (!timeStr) return '--'
				return formatDate(timeStr)
			},
			
			formatDateTime(timeStr) {
				if (!timeStr) return '--'
				return formatDateTime(timeStr)
			},
			
			getResultType(result) {
				if (!result) return 'default'
				
				switch (result) {
					case '合格':
						return 'success'
					case '不合格':
						return 'error'
					default:
						return 'warning'
				}
			},
			
			getFlowNodeName(nodeCode) {
				if (!nodeCode) return '--'
				
				const node = Object.values(FLOW_NODES).find(n => n.code === nodeCode)
				return node ? node.name : nodeCode
			},
			
			resetFilter() {
				this.pmode = ''
				this.presult = ''
				this.cproject = ''
				this.index = 0
				this.presultindex = 0
				this.cprojectIndex = 0
				this.getCpatrol({})
			},
			goReform(pid){
				uni.redirectTo({
					url:"/pages/reform/reform?pid="+pid
				})
			},
			//提交限期整改
			reform(pid){
				var data ={}
				data = {pids:pid}
				request({
					url: "/patrol2/limitRectifySubmit",
					method: "POST",
					data: data,
					header: {
						'Content-Type': 'application/x-www-form-urlencoded',
						'cookie': uni.getStorageSync('cookie')
					}
				}).then(res => {
					if (res.data.success == true) {
						uni.showToast({
							title: '操作成功',
							
						})
						this.getCpatrol()
					} else {
						uni.showToast({
							title: res.data.msg,
							
						})
					}
				})
			},
			//二级审核通过
			approved2(pid){
				var data ={}
				data = {pids:pid}
				request({
					url: "/patrol2/limitRectifyPass2",
					method: "POST",
					data: data,
					header: {
						'Content-Type': 'application/x-www-form-urlencoded',
						'cookie': uni.getStorageSync('cookie')
					}
				}).then(res => {
					
					if (res.data.success == true) {
						uni.showToast({
							title: '操作成功',
							
						})
						this.getCpatrol()
					} else {
						uni.showToast({
							title: res.data.msg,
							
						})
					}
				})
			},
			reject2(pid){
				var data ={}
				uni.redirectTo({
					url:"/pages/reject2/reject2?pid="+pid
				})
			},
			//一级复查通过
			review1Pass(pid){
				var data ={}
				data = {pids:pid}
				request({
					url: "/patrol2/checkLimitRectifyPass1",
					method: "POST",
					data: data,
					header: {
						'Content-Type': 'application/x-www-form-urlencoded',
						'cookie': uni.getStorageSync('cookie')
					}
				}).then(res => {
					
					if (res.data.success == true) {
						uni.showToast({
							title: '操作成功',
							
						})
						this.getCpatrol()
					} else {
						uni.showToast({
							title: res.data.msg,
							
						})
					}
				})
			},
			//一级复查驳回
			review1reject(pid){
				var data ={}
				data = {pids:pid}
				var data ={}
				uni.redirectTo({
					url:"/pages/reject2/reject2?pid="+pid
				})
			},
			
			
			//二级复查通过
			review2Pass(pid){
				var data ={}
				data = {pids:pid}
				request({
					url: "/patrol2/checkLimitRectifyPass2",
					method: "POST",
					data: data,
					header: {
						'Content-Type': 'application/x-www-form-urlencoded',
						'cookie': uni.getStorageSync('cookie')
					}
				}).then(res => {
					
					if (res.data.success == true) {
						uni.showToast({
							title: '操作成功',
							
						})
						this.getCpatrol()
					} else {
						uni.showToast({
							title: res.data.msg,
							
						})
					}
				})
			},
			//二级复查驳回
			review2reject(pid){
				var data ={}
				data = {pids:pid}
				request({
					url: "/patrol2/checkLimitRectifyDeny2",
					method: "POST",
					data: data,
					header: {
						'Content-Type': 'application/x-www-form-urlencoded',
						'cookie': uni.getStorageSync('cookie')
					}
				}).then(res => {
					
					if (res.data.success == true) {
						uni.showToast({
							title: '操作成功',
							
						})
						this.getCpatrol()
					} else {
						uni.showToast({
							title: res.data.msg,
							
						})
					}
				})
			},
			uploadReform(pid){
				var data ={}
				data = {pids:pid}
			
				request({
					url: "/patrol2/handleRectify1",
					method: "POST",
					data: data,
					header: {
						'Content-Type': 'application/x-www-form-urlencoded',
						'cookie': uni.getStorageSync('cookie')
					}
				}).then(res => {
					
					if (res.data.success == true) {
						uni.showToast({
							title: '操作成功',
							
						})
						this.getCpatrol()
					} else {
						uni.showToast({
							title: res.data.msg,
							
						})
					}
				})
			},
			updateCpatrol(item) {
				if (!item || !item.pid) return
				
				uni.navigateTo({
					url: `/pages/updateCpatrol/updateCpatrol?pid=${item.pid}&ptype=${item.ptype_val || ''}`
				})
			},
			
			addcapatrol() {
				if (!this.cprojectId) {
					uni.showToast({
						title: '项目信息不存在',
						icon: 'none'
					})
					return
				}
				
				uni.redirectTo({
					url: `/pages/add_cipdetail/add_cipdetail?cprojectId=${this.cprojectId}`
				})
			},
			filter() {
				const data = {}
				
				if (this.pmode && this.pmode.toString().trim() !== '') {
					data.query_pmode = this.pmode
				}
				if (this.presult && this.presult.toString().trim() !== '') {
					data.query_presult = this.presult
				}
				if (this.cproject && this.cproject.toString().trim() !== '') {
					data.query_cproject = this.cproject
				}
				
				this.getCpatrol(data)
			},
			//查看明细
			goCpatrolDetail(pid){
				
				uni.redirectTo({
					url:"/pages/cpatrol_detail/cpatrol_detail?pid="+pid
				})
			},
			// 获取巡查单列表
			async getCpatrol(filterData = {}) {
				try {
					this.isLoading = true
					
					const data = {
						...filterData,
						sort: 'updatetime',
						order: 'desc',
						query_cproject: this.cprojectId
					}
					
					let uri = ''
					if (this.userInfo.dept && this.userInfo.dept.deptName === '市场科') {
						data.query_ptype = '01'
						uri = '/thirdGrid/query/c_cpatrol-m_cpatrol'
					} else if (this.userInfo.dept && this.userInfo.dept.deptName === '安全科') {
						data.query_ptype = '02'
						uri = '/thirdGrid/query/c_spatrol-m_spatrol'
					} else if (this.userInfo.dept && this.userInfo.dept.deptName === '质监科') {
						data.query_ptype = '03'
						uri = '/thirdGrid/query/c_qpatrol-m_qpatrol'
					} else {
						uri = '/thirdGrid/query/c_patrol2-m_patrol2'
					}
					
					const response = await request({
						url: uri,
						method: 'POST',
						data: data,
						header: {
							'Content-Type': 'application/x-www-form-urlencoded',
							'cookie': uni.getStorageSync('cookie')
						}
					})
					
					if (response.data.success) {
						this.cpatrolList = response.data.rows || []
					} else {
						uni.showToast({
							title: response.data.msg || '加载失败',
							icon: 'none'
						})
					}
				} catch (error) {
					console.error('获取巡查单列表失败:', error)
					uni.showToast({
						title: '网络错误，请稍后重试',
						icon: 'none'
					})
				} finally {
					this.isLoading = false
				}
			},
			
			
			
			
			
			
			
			// 筛选相关方法
			bindPickerChanges(e) {
				this.index = e.target.value
				this.pmode = (this.pModes[this.index] && this.pModes[this.index].id) || ''
			},
			
			bindPresultChanges(e) {
				this.presultindex = e.target.value
				this.presult = (this.presults[this.presultindex] && this.presults[this.presultindex].id) || ''
			},
			
			bindProtectChanges(e) {
				this.cprojectIndex = e.target.value
				this.cproject = (this.cprojects[this.cprojectIndex] && this.cprojects[this.cprojectIndex].id) || ''
			},
			
			chargeFilter() {
				this.showFilter = !this.showFilter
			},
			async getPmode() {
				try {
					const response = await request({
						url: '/thirdWidget/comboJson/c_cpatrol-pmode',
						method: 'POST',
						header: {
							'Content-Type': 'application/x-www-form-urlencoded',
							'cookie': uni.getStorageSync('cookie')
						}
					})
					
					if (response.data.code === '200') {
						this.pModes = response.data.data.map(item => ({
							id: item.id || ' ',
							cn: item.cn || '无'
						}))
						this.pmode = (this.pModes[0] && this.pModes[0].id) || ''
					}
				} catch (error) {
					console.error('获取巡查模式失败:', error)
				}
			},
			async getPresults() {
				try {
					const response = await request({
						url: '/thirdWidget/comboJson/c_cpatrol-presult',
						method: 'POST',
						header: {
							'Content-Type': 'application/x-www-form-urlencoded',
							'cookie': uni.getStorageSync('cookie')
						}
					})
					
					if (response.data.code === '200') {
						this.presults = response.data.data.map(item => ({
							id: item.id || ' ',
							cn: item.cn || '无'
						}))
						this.presult = (this.presults[0] && this.presults[0].id) || ''
					}
				} catch (error) {
					console.error('获取巡查结果失败:', error)
				}
			},
			async getProjects() {
				try {
					const response = await request({
						url: '/thirdWidget/findJson?code=c_cpatrol&field=cproject',
						method: 'POST',
						header: {
							'Content-Type': 'application/x-www-form-urlencoded',
							'cookie': uni.getStorageSync('cookie')
						}
					})
					
					if (response.data.success) {
						this.cprojects = [{ id: ' ', cn: '无' }]
						response.data.rows.forEach(item => {
							this.cprojects.push({
								id: item.cpid || ' ',
								cn: item.csname || '无'
							})
						})
						this.cproject = (this.cprojects[0] && this.cprojects[0].id) || ''
					}
				} catch (error) {
					console.error('获取项目列表失败:', error)
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
@import '@/styles/variables.scss';

.cpatrol-page {
	min-height: 100vh;
	padding: $spacing-lg;
	background: linear-gradient(135deg, #1890ff 0%, #096dd9 100%);
}

.page-header {
	margin-bottom: $spacing-lg;
	
	.header-content {
		display: flex;
		align-items: center;
		justify-content: space-between;
		margin-bottom: $spacing-md;
	}
	
	.page-title {
		font-size: $font-size-xl;
		font-weight: 600;
		color: $text-white;
		text-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.3);
	}
	
	.task-count {
		font-size: $font-size-sm;
		color: rgba(255, 255, 255, 0.9);
		background: rgba(255, 255, 255, 0.2);
		padding: $spacing-xs $spacing-sm;
		border-radius: $border-radius-lg;
	}
	
	.header-actions {
		display: flex;
		gap: $spacing-sm;
	}
	
	.action-btn {
		display: flex;
		align-items: center;
		gap: $spacing-xs;
		padding: $spacing-sm $spacing-md;
		background: rgba(255, 255, 255, 0.15);
		border-radius: $border-radius-base;
		color: $text-white;
		font-size: $font-size-sm;
		font-weight: 500;
		cursor: pointer;
		transition: all 0.3s ease;
		
		&:active {
			background: rgba(255, 255, 255, 0.25);
			transform: scale(0.98);
		}
		
		.btn-icon {
			font-size: $font-size-base;
		}
		
		.btn-text {
			font-size: $font-size-sm;
		}
	}
}

.filter-section {
	margin-bottom: $spacing-lg;
	
	.filter-card {
		background: $white;
		border-radius: $border-radius-lg;
		padding: $spacing-xl;
		box-shadow: $shadow-md;
		
		.filter-title {
			font-size: $font-size-lg;
			font-weight: 600;
			color: $text-primary;
			margin-bottom: $spacing-lg;
			padding-bottom: $spacing-sm;
			border-bottom: 2px solid $primary-color;
		}
		
		.filter-content {
			display: flex;
			flex-direction: column;
			gap: $spacing-md;
		}
		
		.filter-row {
			display: flex;
			align-items: center;
			gap: $spacing-md;
			
			.filter-label {
				font-size: $font-size-base;
				color: $text-secondary;
				font-weight: 500;
				min-width: 120rpx;
			}
			
			.filter-picker {
				flex: 1;
				padding: $spacing-sm $spacing-md;
				background: $gray-50;
				border-radius: $border-radius-base;
				border: 1px solid $border-color;
				
				.picker-text {
					font-size: $font-size-base;
					color: $text-primary;
				}
			}
		}
		
		.filter-actions {
			display: flex;
			gap: $spacing-md;
			justify-content: center;
			margin-top: $spacing-lg;
			
			.filter-btn {
				flex: 1;
				padding: $spacing-md;
				border-radius: $border-radius-base;
				text-align: center;
				font-size: $font-size-base;
				font-weight: 600;
				cursor: pointer;
				transition: all 0.3s ease;
				
				&.primary {
					background: $primary-color;
					color: $text-white;
					
					&:active {
						background: darken($primary-color, 10%);
					}
				}
				
				&.secondary {
					background: $gray-100;
					color: $text-secondary;
					border: 1px solid $border-color;
					
					&:active {
						background: $gray-200;
					}
				}
			}
		}
	}
}

.empty-state {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	padding: 120rpx $spacing-xl;
	background: $white;
	border-radius: $border-radius-lg;
	box-shadow: $shadow-md;
	
	.empty-icon {
		font-size: 120rpx;
		margin-bottom: $spacing-lg;
		opacity: 0.6;
	}
	
	.empty-title {
		font-size: $font-size-lg;
		font-weight: 600;
		color: $text-primary;
		margin-bottom: $spacing-sm;
	}
	
	.empty-desc {
		font-size: $font-size-sm;
		color: $text-secondary;
		text-align: center;
		line-height: 1.5;
		margin-bottom: $spacing-lg;
	}
	
	.empty-action {
		padding: $spacing-md $spacing-xl;
		background: $primary-color;
		color: $text-white;
		border-radius: $border-radius-base;
		cursor: pointer;
		transition: all 0.3s ease;
		
		&:active {
			background: darken($primary-color, 10%);
			transform: scale(0.98);
		}
		
		.action-text {
			font-size: $font-size-base;
			font-weight: 600;
		}
	}
}

.patrol-list {
	display: flex;
	flex-direction: column;
	gap: $spacing-lg;
}

.patrol-card {
	background: $white;
	border-radius: $border-radius-lg;
	padding: $spacing-xl;
	box-shadow: $shadow-md;
	position: relative;
	transition: all 0.3s ease;
	cursor: pointer;
	border-left: 4px solid $primary-color;
	
	&:active {
		transform: translateY(2rpx);
		box-shadow: $shadow-sm;
	}
}

.card-header {
	display: flex;
	align-items: center;
	justify-content: space-between;
	margin-bottom: $spacing-lg;
	gap: $spacing-md;
}

.task-time {
	display: flex;
	align-items: center;
	gap: $spacing-xs;
	
	.time-icon {
		font-size: $font-size-sm;
		color: $text-secondary;
	}
	
	.time-text {
		font-size: $font-size-sm;
		color: $text-secondary;
	}
}

.project-name {
	margin-bottom: $spacing-lg;
	
	.name-text {
		font-size: $font-size-lg;
		font-weight: 600;
		color: $text-primary;
		line-height: 1.4;
	}
}

.patrol-info {
	display: flex;
	flex-direction: column;
	gap: $spacing-sm;
	margin-bottom: $spacing-lg;
}

.info-row {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: $spacing-sm;
	background: $gray-50;
	border-radius: $border-radius-base;
	
	.info-label {
		font-size: $font-size-sm;
		color: $text-secondary;
		font-weight: 500;
		min-width: 140rpx;
	}
	
	.info-value {
		font-size: $font-size-sm;
		color: $text-primary;
		font-weight: 500;
		
		&.flow-node {
			color: $primary-color;
			font-weight: 600;
		}
	}
}

.action-hint {
	text-align: center;
	padding-top: $spacing-md;
	border-top: 1px solid lighten($border-color, 10%);
	
	.hint-text {
		font-size: $font-size-xs;
		color: $text-muted;
		font-style: italic;
	}
}
</style>